package cn.xiaolang.thread.concurrent;

import org.junit.Test;

/**
 * wait方法调用一定要放在对应锁对象的同步代块中
 *
 * @author fuhw/Dean
 * @date 2020-05-19
 */
public class WaitMethodTest {

    private Object object = new Object();
    private Object anotherObject = new Object();

    /**
     * 会抛出异常：
     * java.lang.IllegalMonitorStateException
     *
     * @throws InterruptedException
     */
    @Test
    public void testWait() {
        try {
            object.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 依然会抛出异常：
     * java.lang.IllegalMonitorStateException
     */
    @Test
    public void testWaitBySync() {
        synchronized (object) {
            try {
                /**
                 * wait方法调用的要求：
                 * 一定要处于锁对象的同步块中才可以调用Object的wait方法，避免出现lost of weak的场景
                 * 示例：object.wait();不会抛出异常
                 */
                anotherObject.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


}
